import * as echarts from 'echarts';

import type { EChartsOption } from "echarts"
import { unref, onMounted, nextTick, reactive, watchEffect, onUnmounted } from "vue"
import type { Ref } from "vue"

export default function useECharts(el: Ref<HTMLDivElement>,
    theme: 'light' | 'dark' | 'default' = 'dark') {
    //echarts图实例
    let echartInstance: NonNullable<any> = null;

    //setInterNal监听dom宽高变化
    const echartDomSize = reactive<{
        interval: any,
        width: number,
        height: number,
    }>({
        interval: null,//定时器
        width: 0,
        height: 0,
    })

    //初始化echarts图
    onMounted(() => {
        if (!unref(el.value)) return
        echartInstance = echarts.init(el.value, theme);

        echartDomSize.interval = setInterval(() => {
            const { offsetWidth, offsetHeight } = el.value
            echartDomSize.width = offsetWidth
            echartDomSize.height = offsetHeight
        }, 300)
    })

    onUnmounted(() => { clearInterval(echartDomSize.interval) })

    //设置默认样式数据
    const defaultOption: EChartsOption = {
        backgroundColor: theme == 'dark' ? 'rgba(0,0,0,0)' : 'rgba(255,555,255,1)',
        // color: ["#c12e34", "#e6b600", "#0098d9", "#2b821d", "#005eaa", "#339ca8", "#cda819", "#32a487"]
    }

    function addDefaultOption(option: EChartsOption) {
        Object.assign(defaultOption, option)
    }


    async function setOption(option: EChartsOption) {
        if (!unref(el.value)) {
            await nextTick();
            echartInstance = echarts.init(el.value, theme);
        }
        if (!echartInstance) throw new Error("echarts 实例没有创建成功");

        echartInstance?.setOption(Object.assign(defaultOption, option), true)
    }

    function resize() {
        echartInstance?.resize()
    }

    //监听dom大小变化
    watchEffect(() => { if (echartDomSize.width && echartDomSize.height) resize() })

    return {
        addDefaultOption,
        setOption,
        resize,
        echartInstance
    }
}
